package com.example.helloworldtext2.api;

import android.util.Log;

import com.example.helloworldtext2.model.Article;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 视频相关API封装类
 * 用于处理视频数据的网络请求
 */
public class ArticleApi {
    private static final String TAG = "VideoApi";
    private static final String BASE_URL = "https://test.cengjifou.com/api/article/lists";
    private OkHttpClient client;

    public ArticleApi() {
        client = new OkHttpClient();
    }
    
    /**
     * 解析视频数据
     * @param videoArray 视频数据数组
     * @return 解析后的视频列表
     * @throws JSONException 解析异常
     */
    public List<Article> parseVideoData(JSONArray videoArray) throws JSONException {
        List<Article> videoList = new ArrayList<>();

        for (int i = 0; i < videoArray.length(); i++) {
            JSONObject videoObject = videoArray.getJSONObject(i);

            int id = videoObject.getInt("id");
            String title = videoObject.getString("title");
            String description = videoObject.optString("abstract", "");

            // 获取视频URL（优先使用video_path，如果没有则使用original_video_path）
            String videoUrl = videoObject.optString("video_path", "");
            if (videoUrl.isEmpty()) {
                videoUrl = videoObject.optString("original_video_path", "");
            }

            // 获取封面图片URL（从image数组中获取第一张图片）
            String coverImageUrl = "";
            if (videoObject.has("image") && videoObject.getJSONArray("image").length() > 0) {
                coverImageUrl = videoObject.getJSONArray("image").getString(0);
            }

            // 获取作者信息
            String authorName = videoObject.optString("author", "");
            String authorAvatar = videoObject.optString("author_avatar", "");

            // 获取视频时长
            String duration = "0";
            if (videoObject.has("video_info") && videoObject.getJSONObject("video_info").has("duration")) {
                duration = String.valueOf(videoObject.getJSONObject("video_info").getDouble("duration"));
            }

            // 获取话题标签
            List<String> topics = new ArrayList<>();
            if (videoObject.has("topicList")) {
                JSONArray topicsArray = videoObject.getJSONArray("topicList");
                for (int j = 0; j < topicsArray.length(); j++) {
                    JSONObject topicObject = topicsArray.getJSONObject(j);
                    topics.add(topicObject.optString("name", ""));
                }
            }

            Article article = new Article(
                    id, title, description, videoUrl, coverImageUrl,
                    authorName, authorAvatar, topics, duration
            );

            videoList.add(article);
        }
        
        return videoList;
    }

    /**
     * 获取视频列表
     * @param page 页码
     * @param pageSize 每页数据量
     * @param listener 请求结果监听器
     */
    public void getVideoList(int page, int pageSize, VideoListListener listener) {
        // 构建带参数的URL
        String url = BASE_URL +
                "?page_no=" + page +
                "&page_size=" + pageSize +
                "&scene=videoList" +
                "&ctype=video" +
                "&recommend=1" +
                "&follow=0" +
                "&articleId=0" +
                "&random_article_id=0";

        Request request = new Request.Builder()
                .url(url)
                .addHeader("User-Agent", "Android App")
                .build();

        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.e(TAG, "Failed to fetch video data", e);
                listener.onError("网络请求失败: " + e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                if (!response.isSuccessful()) {
                    listener.onError("请求失败: " + response.code());
                    return;
                }

                try {
                    String responseData = response.body().string();
                    JSONObject jsonObject = new JSONObject(responseData);

                    // 解析API返回的数据
                    if (jsonObject.has("data") && jsonObject.getJSONObject("data").has("lists")) {
                        JSONArray videoArray = jsonObject.getJSONObject("data").getJSONArray("lists");

                        // 获取分页信息
                        JSONObject dataObject = jsonObject.getJSONObject("data");
                        int totalCount = dataObject.getInt("count");
                        int pageSize = dataObject.getInt("page_size");
                        boolean hasMore = (page * pageSize) < totalCount;

                        listener.onSuccess(videoArray, page, hasMore);
                    } else {
                        listener.onError("数据格式错误");
                    }
                } catch (JSONException e) {
                    Log.e(TAG, "Error parsing JSON response", e);
                    listener.onError("数据解析失败: " + e.getMessage());
                }
            }
        });
    }

    /**
     * 视频列表请求监听器接口
     */
    public interface VideoListListener {
        /**
         * 请求成功回调
         * @param videoArray 视频数据数组
         * @param page 当前页码
         * @param hasMore 是否还有更多数据
         */
        void onSuccess(JSONArray videoArray, int page, boolean hasMore);

        /**
         * 请求失败回调
         * @param error 错误信息
         */
        void onError(String error);
    }
}